package dd.lo.chapter12;

import dd.lo.util.ImageUtils;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.io.ByteArrayInputStream;
import java.io.File;

/**
 * In this exercise, we learn to experiment with parameters by setting good lowThresh and highThresh values in cv::Canny() . Load an image with suitably interesting line structures. We’ll use three different high:low threshold settings of 1.5:1, 2.75:1, and 4:1.
 * Report what you see with a high setting of less than 50 .
 * Report what you see with high settings between 50 and 100 .
 * Report what you see with high settings between 100 and 150 .
 * Report what you see with high settings between 150 and 200 .
 * Report what you see with high settings between 200 and 250 .
 * Summarize your results and explain what happens as best you can.
 */
public class Exercise1 extends Application {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        launch(args);
    }

    private static final int DEFAULT_WIDTH = 1080;
    private static final int DEFAULT_HEIGHT = 768;

    private static final int[][] THRESHOLDS = new int[][]{{0, 50}, {50, 100}, {100, 150}, {150, 200}, {200, 250}};

    private Mat srcImg;

    private int threshIdx = 0;

    private ImageView imageView;

    private void applyCanny() {
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() {
                if (null == srcImg) return null;
                Mat dst = new Mat();
                srcImg.copyTo(dst);
                Imgproc.cvtColor(dst, dst, Imgproc.COLOR_BGR2GRAY);
                int[] thresholdRange = THRESHOLDS[threshIdx];
                Imgproc.Canny(dst, dst, thresholdRange[0], thresholdRange[1]);
                //调整图片大小以用于展示
                ImageUtils.fitImgSize(dst, DEFAULT_WIDTH, DEFAULT_HEIGHT);
                MatOfByte buffer = new MatOfByte();
                Imgcodecs.imencode(".jpeg", dst, buffer);
                Platform.runLater(() -> imageView.setImage(new Image(new ByteArrayInputStream(buffer.toArray()))));
                return null;
            }
        };
        new Thread(task).start();
    }

    @Override
    public void start(Stage stage) {
        //File chooser
        Button imageChooser = new Button("选择图片");
        imageChooser.setOnMouseClicked(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("请选择图片");
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "/Downloads")
            );
            fileChooser.getExtensionFilters().addAll(
//                    new FileChooser.ExtensionFilter("All Images", "*.*"),
                    new FileChooser.ExtensionFilter("JPEG", "*.jpeg"),
                    new FileChooser.ExtensionFilter("WEBP", "*.webp"),
                    new FileChooser.ExtensionFilter("PNG", "*.png"),
                    new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                    new FileChooser.ExtensionFilter("GIF", "*.gif"),
                    new FileChooser.ExtensionFilter("BMP", "*.bmp")
            );
            File imgFile = fileChooser.showOpenDialog(stage);
            if (null == imgFile) {
                System.out.println("用户取消选中文件");
                return;
            }
            //读取一张图片
            srcImg = Imgcodecs.imread(imgFile.getAbsolutePath(), Imgcodecs.IMREAD_UNCHANGED);
            if (srcImg.empty()) {
                throw new RuntimeException("图片读取失败");
            }
            applyCanny();
        });
        //Mode indicator
        Text threshText = new Text(String.format("当前范围：%d ~ %d", THRESHOLDS[threshIdx][0], THRESHOLDS[threshIdx][1]));
        Button prevButton = new Button("上一个范围");
        prevButton.setOnMouseClicked(e -> {
            --threshIdx;
            if (threshIdx < 0) threshIdx = THRESHOLDS.length - 1;
            threshText.setText(String.format("当前范围：%d ~ %d", THRESHOLDS[threshIdx][0], THRESHOLDS[threshIdx][1]));
            applyCanny();
        });
        Button nextButton = new Button("下一个范围");
        nextButton.setOnMouseClicked(e -> {
            ++threshIdx;
            if (threshIdx >= THRESHOLDS.length) threshIdx = 0;
            threshText.setText(String.format("当前范围：%d ~ %d", THRESHOLDS[threshIdx][0], THRESHOLDS[threshIdx][1]));
            applyCanny();
        });
        //Exit button
        Button exitButton = new Button("关闭");
        exitButton.setOnMouseClicked(e -> {
            Platform.exit();
        });
        FlowPane bottomControl = new FlowPane();
        bottomControl.getChildren().addAll(imageChooser, prevButton, threshText, nextButton, exitButton);
        bottomControl.setPrefHeight(50);
        BorderPane root = new BorderPane();
        imageView = new ImageView();
        root.setCenter(imageView);
        root.setBottom(bottomControl);
        Scene scene = new Scene(root, DEFAULT_WIDTH, DEFAULT_HEIGHT + 50);
        stage.setScene(scene);
        stage.setTitle("Exercise1 - Canny applying under different ranges");
        stage.setResizable(false);
        stage.show();
    }
}
